import { Prisma } from '@prisma/client';
import prisma from '@/server/lib/prisma';
import { RoleSchema } from '@/server/lib/zodSchema';

export default defineEventHandler(async (event) => {
  try {
    const body = await readBody(event);
    RoleSchema.parse(body); // 校验参数

    // 角色名称和权限字符是否已存在
    const isRoleKey = await prisma.sys_role.findFirst({
      where: {
        roleId: {
          not: body.roleId
        },
        roleKey: body.roleKey
      }
    })
    if (isRoleKey) {
      return {
        code: 400,
        msg: '权限字符已存在'
      }
    }

    const isRoleName = await prisma.sys_role.findFirst({
      where: {
        roleId: {
          not: body.roleId,
        },
        roleName: body.roleName
      }
    })
    if (isRoleName) {
      return {
        code: 400,
        msg: '权限名称已存在'
      }
    }

    // 参数
    const data: Prisma.sys_roleUpdateInput = {
      roleKey: body.roleKey,
      roleName: body.roleName,
      roleSort: Number(body.roleSort),
      status: body.status,
      remark: body.remark,
    }
    const result = await prisma.sys_role.update({
      where: {
        roleId: Number(body.roleId)
      },
      data,
      include: {
        menus: true,
      }
    })

    if (body.menus && Array.isArray(body.menus)) {
      const createData: any = [];
      body.menus.map((menuId: number) => {
        createData.push({
          roleId: Number(body.roleId),
          menuId: menuId,
        })
      })
      await prisma.sys_role_menu.deleteMany({
        where: {
          roleId: Number(body.roleId)
        }
      })
      await prisma.sys_role_menu.createMany({
        data: createData
      })
    }

    return {
      code: 200,
      data: result,
      msg: '更新成功'
    }
  } catch (error: any) {
    const err = JSON.parse(error);
    return {
      code: 400,
      msg: err[0].message || '未知错误',
    }
  } finally {
    await prisma.$disconnect(); // 关闭连接
  }
})